package en.edu.zucc.pb.loginapplication.activity;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;

import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.stetho.Stetho;

import java.util.List;
import java.util.concurrent.ExecutionException;

import en.edu.zucc.pb.loginapplication.AppDatabase;
import en.edu.zucc.pb.loginapplication.HomeActivity;
import en.edu.zucc.pb.loginapplication.R;
import en.edu.zucc.pb.loginapplication.dao.UserDao;
import en.edu.zucc.pb.loginapplication.db.Repository;
import en.edu.zucc.pb.loginapplication.entity.User;
import en.edu.zucc.pb.loginapplication.fragment.SettingFragment;
import en.edu.zucc.pb.loginapplication.repository.UserRepository;
import en.edu.zucc.pb.loginapplication.task.GetByUsernameTask;
import en.edu.zucc.pb.loginapplication.util.Security;

public class LoginActivity extends AppCompatActivity implements
        View.OnClickListener {

    Button btnToHome;
    LinearLayout main_content;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_main);
        setContentView(R.layout.activity_login);
        Log.e("tag", "finished");
        btnToHome = findViewById(R.id.btn_to_home);
//        btnToHome.
//        https://blog.csdn.net/weixin_33810006/article/details/93024770
        btnToHome.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) { //使用匿名的Button实例

                //抽象接口的内部方法的实现
                Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
                startActivity(intent);
            }
        });
//        btnToHome
//        btn_to_bookkeeping

        findViewById(R.id.btn_to_bookkeeping).setOnClickListener(this);
        findViewById(R.id.btn_login).setOnClickListener(this);
        findViewById(R.id.link_signup).setOnClickListener(this);
        findViewById(R.id.btn_to_acti_b).setOnClickListener(this);
        findViewById(R.id.btn_to_tab).setOnClickListener(this);
        Stetho.initializeWithDefaults(this);
//        https://blog.csdn.net/code_hero666/article/details/80282394


//        main_content = findViewById(R.id.main_content);
//        main_content.getChildAt()
        initDatabase();
    }

    private AppDatabase database;
//    UserDao userDao;
//    UserRepository userRepository;

    void initDatabase() {

//        database = AppDatabase.getDatabase(getApplicationContext());
//        userDao = database.getUserDao();
        //获取Database
//        AppDatabase db = Room.databaseBuilder(getApplicationContext(),
//                AppDatabase.class, DATABASE_NAME).build();

//        userRepository = new UserRepository(this);
        repository=new Repository(this);
    }
    Repository repository;

    private static final String TAG = "LoginActivity";

    void login() throws ExecutionException, InterruptedException {

//        Record record;
//        record.set
        TextView input_email = findViewById(R.id.input_email);
        String username = input_email.getText().toString();
        TextView input_password = findViewById(R.id.input_password);
        String password = input_password.getText().toString();
//room select 不用写代码 和 jpa
//        List<User> byUsername = userDao.getByUsername(username);
//        每个查询都要一个 task 那就奇怪了啊

        GetByUsernameTask getByUsernameTask = new GetByUsernameTask(database);
//        getByUsernameTask.setUsername(username);
//        AsyncTask<Void, Void, List<User>> execute = getByUsernameTask.execute();
//        List<User> byUsername = execute.get();

        User user1 = new User();
        user1.setUsername(username);
        List<User> byUsername = repository.getUserRepository().selectBy(user1);

//        List<User> byUsername = userRepository.getByUsername(username);
        if (byUsername == null || byUsername.size() <= 0) {
            return;
        }
        User user = byUsername.get(0);
        String savedPassword = user.getPassword();

//        String oldPassword = Prefs.getString(PREF_PASSWORD, "");
//        String password = passwordEditText.getText().toString();
        // The check is done on password's hash stored in preferences
        boolean pswdOk = Security.md5(password).equals(savedPassword);
//          点击确认密码之后 验证一下
        if (!pswdOk) {
            String msg = "密码不正确";
            Log.i(TAG, msg);
            Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
            return;
        }
        Intent intent = new Intent(this, BookkeepingActivity.class);
        startActivity(intent);
    }

    void signUp() {
        Intent intent = new Intent(this, RegisterActivity.class);
        startActivity(intent);
    }

    /**
     * 跳转配置页面
     *
     * @param view
     */
    public void onSetting(View view) {
//        R.id
//        getSupportFragmentManager().beginTransaction().add(R.id.container,new Fragment).commit();

//        之前的 设置还是有记住的
        this.getFragmentManager().beginTransaction()
//        this.getSupportFragmentManager().beginTransaction()
                .replace(android.R.id.content, new SettingFragment())
                .commit();
    }

//————————————————
//    版权声明：本文为CSDN博主「康耶」的原创文章，遵循CC 4.0 BY-SA版权协议，转载请附上原文出处链接及本声明。
//    原文链接：https://blog.csdn.net/qwer492915298/article/details/88063854

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {

            case R.id.btn_to_bookkeeping:
                intent = new Intent(this, BookkeepingActivity.class);
                startActivity(intent);
                break;
            case R.id.btn_login:
                try {
                    login();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.link_signup:
                signUp();
                break;
            case R.id.btn_to_acti_b:
                toActivityB();
                break;
            case R.id.btn_to_tab:
//                toActivityB();
//                如果是 根据布局来 文件夹，取名都是 activity 那补全就不好了
//                但是 就算文件夹有名字了 activity 还是可以取名为TabActivity
//                    好像也没事
                toActivity(TabActivity.class);
                break;

//            case R.id.btn_to_setting:
//                toSetting();
//                break;

        }
    }


    void toActivity( Class<?> cls){
        Intent intent = new Intent(this, cls);
        startActivity(intent);
    }

    void toActivityB(){
        Intent intent = new Intent(this, MainActivityB.class);
        startActivity(intent);
    }

    //    看来是必须要   void toSetting(View view){
    public void toSetting(View view) {
        Intent intent = new Intent(this, SettingActivity.class);
        startActivity(intent);
    }
}
